export default class Compressor {
    constructor(props){
    }
    static urlToImage (url,fn){
        var img = new Image();
        img.src = url;
        img.onload = function(){
          fn(img);
        }
    };
    static imagetoCanvas(image){
        var cvs = document.createElement("canvas");
        var ctx = cvs.getContext('2d');
        cvs.width = image.width;
        cvs.height = image.height;
        ctx.drawImage(image, 0, 0, cvs.width, cvs.height);
        return cvs ;
    };
    static canvasResizetoFile(canvas,quality,fn){
        canvas.toBlob(function(blob) {
          fn(blob);
        },'image/jpeg',quality);
    };
    static canvasResizetoDataURL(canvas,quality){
        return canvas.toDataURL('image/jpeg',quality);
    };
    static filetoDataURL(file,fn){
        var reader = new FileReader();
        reader.onloadend = function(e){
          fn(e.target.result);
        };
        reader.readAsDataURL(file);
    };
    static dataURLtoImage(dataurl,fn){
        var img = new Image();
        img.onload = function() {
          fn(img);
        };
        img.src = dataurl;
    };
    static dataURLtoFile(dataurl) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {type:mime});
    };
    static fileResizetoFile(file,quality,fn){
        Compressor.filetoDataURL(file,function(dataurl){
            Compressor.dataURLtoImage(dataurl,function(image){
                Compressor.canvasResizetoFile(Compressor.imagetoCanvas(image),quality,fn);
            })
        })
    }
}